// pages/pay/index.js
import { getSetting, chooseAddress, openSetting, showModal, showToast, requestPayment } from "../../utils/wx.js";
import {request} from "../../request/index.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    totalPrice: 0,
    totalNum: 0
  },

  onShow(){
    const ad = wx.getStorageSync("address");
    let cart = wx.getStorageSync("cart") || [];

    cart = cart.filter(el => el.checked);
    
    let totalPrice = 0, totalNum = 0;
    cart.forEach(element => {
      totalPrice += element.num * element.goods_price;
      totalNum += element.num;
    });
    
    this.setData({
      cart,
      totalPrice,
      totalNum,
      address: ad
    });

  },

  /**
   * 点击支付
   */
  handleOrderPay(){
    const token = wx.getStorageSync("token");
    if(!token){
      wx.navigateTo({
        url: "/pages/auth/index"
      });
      return;
    }
    console.log("有token了");

    /**
     * 以下步骤需要绑定的是企业小程序账号而不是个人开发者小程序账号，才能完成
     */
    // //创建订单
    // const order_price = this.data.totalPrice, consignee_addr = this.data.address.all;
    // const cart = this.data.cart;
    // let goods = [];
    // cart.forEach(el => {
    //   goods.push({
    //     goods_id: el.goods_id,
    //     goods_number: el.goods_number,
    //     goods_price: el.goods_price
    //   });
    // });
    // const orderParams = {order_price, consignee_addr, goods};
    // let order_number = ''; //获取的订单号
    // //发送请求创建订单：
    // request({url: "/my/orders/create", method: "POST", data: orderParams})
    // .then(res => {
    //   order_number = res.order_number; //订单号
    //   const {pay} = res;
    //   //发起微信支付：
    //   return requestPayment(pay);
    // })
    // .then(res => {
    //   // console.log(res);
    //   //查询后台数据看看订单状态是否支付成功
    //   return request({url: "/my/orders/create", method: "POST", data: order_number})
    // })
    // .then(res => {
    //   console.log("服务器查询到的订单状态：", res);
    //   showToast({title: '支付成功'});
    //   //删除缓存中已支付过的商品：
    //   let newCart = wx.getStorageSync("cart");
    //   newCart = newCart.filter(el => {
    //     return !el.checked;
    //   });
    //   wx.getStorageSync("cart", newCart);
    //   //跳转到订单页面：
    //   wx.navigateTo({url: '/pages/order/index'});
    // })
    // .catch(err => {
    //   console.log(err);
    //   showToast({title: '支付失败'});
    // });

  }

})